package com.unknowpupil.design.iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: <p>
 *  自定义聚合类
 * </p>
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2020/4/28 13:24
 * @Classname: ConcreteMyAggregate
 * @Version: 1.0
 */
public class ConcreteMyAggregate {


    /**
     * 定义容器
     */
    private List<Object> list = new ArrayList<Object>();



    public void addObject(Object obj){
        this.list.add(obj);
    }
    public void removeObject(Object obj){
        this.list.remove(obj);
    }

    public List<Object> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }

    /**
     * 获得迭代器
     */
    public MyIterator createIterator(){
        return new ConcreteIterator();
    }


    /**
     *
     * 使用类部类 定义迭代器，可以之间使用外部类的属性。
     */
    private class ConcreteIterator implements MyIterator{
       // 定义游标 用于记录遍历时位置
       private int cursor;
        @Override
        public void first() {
            cursor = 0;
        }

        @Override
        public void next() {

            if(cursor<list.size()){
                cursor++;
            }
        }

        @Override
        public boolean hasNext() {
            if(cursor<list.size()){
                return true;
            }
            return false;
        }

        @Override
        public boolean isFirst() {
            return cursor==0?true:false;
        }

        @Override
        public boolean isLast() {
            return cursor==list.size()-1?true:false;
        }

        @Override
        public Object getCurrentObj() {
            return list.get(cursor);
        }
    }

}
